package com.bigmi.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bigmi.apis.article.ArticleClientIp;
import com.bigmi.common.baidu.api.CheckContent;
import com.bigmi.file.service.FileStorageService;
import com.bigmi.model.article.Dto.ArticleDto;
import com.bigmi.model.common.dtos.ResponseResult;
import com.bigmi.model.wemedia.pojos.WmChannel;
import com.bigmi.model.wemedia.pojos.WmNews;
import com.bigmi.model.wemedia.pojos.WmSensitive;
import com.bigmi.model.wemedia.pojos.WmUser;
import com.bigmi.utils.common.SensitiveWordUtil;
import com.bigmi.wemedia.mapper.WmChannelMapper;
import com.bigmi.wemedia.mapper.WmNewsMapper;
import com.bigmi.wemedia.mapper.WmSensitiveMapper;
import com.bigmi.wemedia.mapper.WmUserMapper;
import com.bigmi.wemedia.service.WmNewsScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsScanServiceImpl implements WmNewsScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    //百度云审核
    @Autowired
    private CheckContent checkContent;
    //minio
    @Autowired
    private FileStorageService fileStorageService;
    //feign接口调用
    @Autowired
    private ArticleClientIp articleClientIp;
    //查询频道
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;


    @Override
//    @Async//当前方法是异步调用
    public void ScanWmNews(Integer id) {
        //查寻文章
        System.out.println("================="+id);
        if (id!=null){

        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews==null){
            throw new RuntimeException("文章不存在");
        }

        //查询状态，状态必须为1待审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从WmNews表content中提取文本
            // 包含内容图片和封面图片
            Map<String,Object> textAndImg=  handleTextAndImgs(wmNews);
            //自管理敏感词过滤
            Boolean isSensitive= hadleSensitiveScan((String) textAndImg.get("content"),wmNews);
            if (!isSensitive){
                return;
            }
            //审核文本内容，百度云接口
            Boolean isText= handTextScan((String) textAndImg.get("content"),wmNews);
            if (!isText){
                return;
            }
            //审核图片
            Boolean isImage= handImageScan((List<String>) textAndImg.get("images"),wmNews);
            if (!isImage){
                return;
            }
            //审核成功保存app端文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)){
                wmNews.setStatus((short) 3);
                wmNewsMapper.updateById(wmNews);
                throw new RuntimeException("文章审核保存app端保存失败");
            }
            //回填articleId
            wmNews.setArticleId((Long) responseResult.getData());
            updateNews(wmNews, (short) 9,"审核成功");
        }
        }
    }

    /**
     * 自己管理敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private Boolean hadleSensitiveScan(String content, WmNews wmNews) {
        boolean flag=true;
        //获取所有的敏感词
        LambdaQueryWrapper<WmSensitive> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<WmSensitive> select = queryWrapper.select(WmSensitive::getSensitives);
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(select);
        //在WmSensitive获取敏感词转为string类型的list集合
        List<String> stringList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库initMap,返回值为string
        SensitiveWordUtil.initMap(stringList);
        //查看文章中是否包含敏感词
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(content);
        if (stringIntegerMap.size()>0){
            updateNews(wmNews,(short) 2,"当前文章中存在自定义违规内容"+stringIntegerMap);
            flag=false;
        }
        return flag;
    }

    /**
     * //从WmNews表content中提取文本
     * 包含内容图片和封面图片
     */
    private Map<String, Object> handleTextAndImgs(WmNews wmNews) {
        //存储纯文本内容
        StringBuilder stringBuilder =new StringBuilder();
        //存储图片
        List<String> images =new ArrayList<>();
        //从自媒体内容中提取文本和图片
        if (StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                //文本内容
                if (map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }
                //图片内容
                if (map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }
        }
        //封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        Map<String, Object> resultMap =new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);
        return resultMap;
    }

    /**
     * 审核纯文本内容以及标题
     * @param content
     * @param wmNews
     * @return
     */
    private Boolean handTextScan(String content, WmNews wmNews) {
        boolean flag =true;
        if ((wmNews.getTitle() +"-"+content).length()==0){
            return flag;
        }
        //百度云文本审核接口
        Map<String, Object> map = checkContent.TextCensor(wmNews.getTitle()+"-"+content);
        if (map !=null){
            //审核失败
            if (map.get("conclusion").equals("审核失败") || map.get("conclusion").equals("不合规") ){
                updateNews(wmNews, (short) 2, "当前文章内容中存在违规内容");
                flag =false;
            }
            //疑似和文章内容过长进行人工审核
            if (map.get("conclusion").equals("疑似")){
                updateNews(wmNews, (short) 3, "当前文章内容中存在不确定内容，以提交人工审核");
                flag =false;
            }
        }
        return flag;
    }

    /**
     * 审核内容失败修改文章状态
     * @param wmNews
     * @param Status
     * @param reason
     */
    private void updateNews(WmNews wmNews, short Status, String reason) {
        wmNews.setStatus(Status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 图片审核
     */
    private Boolean handImageScan(List<String> images, WmNews wmNews) {
        boolean flag=true;
        if (images == null || images.size()==0){
            return flag;
        }
        //图片可能重复，去重
        images=images.stream().distinct().collect(Collectors.toList());
        //下载图片到minio
        //byte[] bytes = new byte[0];
        for (String image : images) {
            byte[]  bytes = fileStorageService.downLoadFile(image);
            //审核
            Map<String, Object> map = checkContent.ImgCensor(bytes);
            if (map !=null){
                //审核失败
                if (map.get("conclusion").equals("审核失败") || map.get("conclusion").equals("不合规") ){
                    updateNews(wmNews, (short) 2, "当前文章图片中存在违规内容");
                    flag =false;
                    break;
                }
                //疑似人工审核
                if (map.get("conclusion").equals("疑似")){
                    updateNews(wmNews, (short) 3, "当前文章图片中存在不确定内容，以提交人工审核");
                    flag =false;
                    break;
                }
            }
        }

        return flag;
    }

    /**
     * 保存到app端文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto articleDto =new ArticleDto();
        //属性拷贝content
        BeanUtils.copyProperties(wmNews,articleDto);
        //文章布局  0 无图文章   1 单图文章    2 多图文章
        articleDto.setLayout(wmNews.getType());
        //频道查询wmNews中的频道id
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null){
            articleDto.setChannelName(wmChannel.getName());
        }
        //作者id
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        //作者姓名
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            articleDto.setAuthorName(wmUser.getName());
        }
        //在自媒体端存不在文章id 添加在app端文章
        if (wmNews.getArticleId()!=null){
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());
        //不存在id保存
        //调用文章远程接口
        ResponseResult responseResult = articleClientIp.saveArticle(articleDto);
        return responseResult;

    }

}
